//
//  ZCUserInfoViewModel.swift
//  weibo
//
//  Created by Ning Xie on 16/8/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class ZCUserInfoViewModel: NSObject {

    static let sharedUserInfo:ZCUserInfoViewModel = ZCUserInfoViewModel()
    
    var userInfo :ZCUserInfoModel?{
        return ZCUserInfoModel.loadUserInfo()
    }
    
    var isLogin : Bool {
        
        return accessToken != nil
    }
    var accessToken: String? {
        //  判断accesstoken是否为nil
        
        guard let token = userInfo?.access_token else {
            return nil
        }
        
        //  如果accesstoken不为nil,判断accesstoken的时间是否过期
        let result =  userInfo?.expiresDate?.compare(NSDate())
        //  如果是降序表示accesstoken没有过期
        if result == NSComparisonResult.OrderedDescending {
            return token
        } else {
            return nil
        }

    }
    //MARK:获取授权过的Access Token
    func requestAccessToken(code : String,callBack:(isSuccess:Bool)->())
    {
        
        ZCNetworkTools.sharedNetworkTools.requestAccessToken(code) { (response, error) in
            if error != nil{
                callBack(isSuccess: false)
                return
            }
            guard let dic = response as? [String :AnyObject] else{
                print("不是一个合法的字典数据")
                callBack(isSuccess: false)
                return
            }
            let userAccount = ZCUserInfoModel(dic: dic)
            
            
            //MARK:根据用户ID和access_token获取用户信息
            ZCNetworkTools.sharedNetworkTools.requestUserInfo(userAccount, callBack: { (response, error) in
                if error != nil{
                    callBack(isSuccess: false)
                    return
                }
                guard let userDic = response as? [String:AnyObject] else{
                    callBack(isSuccess: false)
                    return
                }
                
//                let userInfo = ZCUserInfoModel(dic: userDic)
                userAccount.name = userDic["name"] as? String
                userAccount.avatar_large = userDic["avatar_large"] as? String
                
                //执行归档方法n
                userAccount.saveUserInfo()
                
                //告诉外界,网络请求获取数据成功,登录成功
                callBack(isSuccess: true)
                
            })
            
        }
    }

}